<template>
  <page-dialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-list="dialogInfo.btList"
  >
    <NewPageFilter
      v-model:query="filterInfo.query.queryMap"
      :query-more-json="true"
      :filter-list="filterInfo.searchList"
      :filter-btn="filterInfo.searchBtn"
    >
    </NewPageFilter>
    <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
      <dialog-table
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :row-key="rowKey"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :highlight-row="highlightRow"
        :check-box="checkBox"
        :reserve-selection="true"
        :checked-row-list="checkedRowList"
        :checkedList="checkBox ? checkedList : []"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-chargeQty="scope">
          {{ qty }}
        </template>
        <template v-slot:col-editQty="scope">
          <el-form-item
            class="margin-bottom"
            v-if="scope.row.codeType === 1 || scope.row.codeType === 4"
            @click.stop=""
          >
            <div class="page-table-input-number-wrapper">
              <div class="page-table-input-number-left">
                <div class="page-table-input-number-item">
                  <el-form-item
                    :prop="`data.${scope.$index}.largeUnitQty`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              validator: $validate.positiveAndZero,
                              trigger: 'blur',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input-number
                      style="width: 100%"
                      v-model.lazy="scope.row.editQty"
                      clearable
                      controls-position="right"
                      :precision="
                        scope.row.qtyOperateMode === 0 ||
                        scope.row.qtyOperateMode === 2
                          ? 0
                          : systemConfig.qty_show_precision
                      "
                      @change="
                        changeLarge(
                          $event,
                          scope.row,
                          `data.${scope.$index}.largeUnitQty`
                        )
                      "
                      :min="0"
                      :max="largeMax(scope.row)"
                    />
                  </el-form-item>
                </div>
                <div
                  class="page-table-input-number-item"
                  v-if="
                    scope.row.unitConvertCoefficient > 1 &&
                    scope.row.qtyOperateMode === 2
                  "
                >
                  <el-form-item>
                    <el-input-number
                      style="width: 100%"
                      v-model.lazy="scope.row.editQty"
                      clearable
                      controls-position="right"
                      :precision="0"
                      :min="0"
                      :max="smallMax(scope.row)"
                      @change="
                        changeSmall(
                          $event,
                          scope.row,
                          `data.${scope.$index}.smallUnitQty`
                        )
                      "
                    />
                  </el-form-item>
                </div>
              </div>
              <div
                class="page-table-input-number-right"
                v-if="scope.row.qtyOperateMode === 2"
              >
                {{ $fn.qtyFormatter(scope.row.editQty) }}
              </div>
            </div>
          </el-form-item>
          <span
            v-else-if="scope.row.codeType === 2 || scope.row.codeType === 3"
            >{{ $fn.qtyFormatter(scope.row.editQty) }}</span
          >
        </template>
      </dialog-table>
    </el-form>
  </page-dialog>
</template>
<script setup name="HisCharging">
import { getCustomizeSetting } from '@/api/customize'
import { getDepotStockCustomizeListPage } from '@/api/stock.js'
const emits = defineEmits()
const { proxy } = getCurrentInstance()

const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: false,
  },
  rowKey: {
    type: String,
    default: 'id',
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  api: {
    type: Function,
    default: getDepotStockCustomizeListPage,
  },
  showDialog: {
    type: Boolean,
    default: false,
  },
  showPrice: {
    type: Boolean,
    default: true,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  queryParams: {
    type: Object,
    default: function () {
      return {}
    },
  },
  tableKey: {
    type: String,
    default: 'HisSpdChargeByPeople-com.slip.spd.entity.dto.his.HisDepotStockDTO',
  },
  checkedList: {
    type: Array,
    default: () => {
      return []
    },
  },
  checkedRowList: {
    type: Array,
    default: () => {
      return []
    },
  },
  qty:{
    type: Number
  }
})
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
// 过滤相关配置
const filterInfo = ref({
  query: {
    page: true,
    customizeUserVO: {},
    queryMap: {},
    queryParams: {},
  },
  searchList: [],
  searchBtn: [{ type: 'button', label: '搜索', event: search }],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  fieldList: [],
})
// 弹窗相关
const dialogInfo = ref({
  title: 'HIS扣费人工处理',
  width: '90%',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      disabled: true,
      event: save,
      show: true,
    },
  ],
})
const selectRow = ref([])

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件shows
  },
})

setData()
function setData() {
  let obj = {
    price: {
      label: '单价',
      value: 'price',
      type: 'column',
      componentType: 'price',
      permission: !props.showPrice,
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
      show: false,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
      type: 'column',
      componentType: 'price',
      permission: !props.showPrice,
      hidden: true,
      show: false,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      componentType: 'price',
      permission: !props.showPrice,
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
      show: false,
    },
    chargeQty: {
      label: '计费数量',
      value: 'chargeQty',
      type: 'slot',
      componentType: 'number',
      formatter: proxy.$fn.qtyFormatter,
      hidden: true,
      show: false,
    },
    editQty: {
      label: '数量',
      value: 'editQty',
      type: 'slot',
      componentType: 'number',
      formatter: proxy.$fn.qtyFormatter,
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
// 获取列表
function getList() {
  proxy.$nextTick(() => {
    tableInfo.value.refresh = Math.random()
  })
}
function search() {
  const _tableInfo = tableInfo.value
  _tableInfo.initCurpage = Math.random()
  _tableInfo.refresh = Math.random()
}
function save() {
  let data = proxy.$fn.deepClone(selectRow.value)
  data.forEach((item) => {
    item.qty = proxy.$fn.deepClone(item.editQty)
    item.calcQty = proxy.$fn.deepClone(item.editCalcQty)
  })
  emits('callback', data, () => {
    handleClose()
  })
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.stockAvailableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.stockAvailableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  // let largeUnitQty = parseInt(
  //   row.stockAvailableCalcQty / row.unitConvertCoefficient
  // )
  // if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
  //   if (largeUnitQty > 0 && e === largeUnitQty) {
  //     let smallUnitQty = parseInt(
  //       row.stockAvailableCalcQty % row.unitConvertCoefficient
  //     )
  //     if (row.smallUnitQty > smallUnitQty) {
  //       row.smallUnitQty = smallUnitQty
  //     }
  //   }
  // }
  // if (row.codeType === 1 || row.codeType === 4) {
  //   row.editCalcQty = proxy.$fn.accAdd(
  //     proxy.$fn.accMul(row.largeUnitQty || 0, row.unitConvertCoefficient || 1),
  //     row.smallUnitQty || 0
  //   )
  //   row.editQty = proxy.$fn.accDiv(
  //     row.editCalcQty || 0,
  //     row.unitConvertCoefficient || 1
  //   )
  //   row.sumAmount = proxy.$fn.accDiv(
  //     proxy.$fn.accMul(row.editCalcQty || 0, parseFloat(row.price || 0)),
  //     row.unitConvertCoefficient || 1
  //   )
  // }
}
function changeSmall(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  // if (row.codeType === 1 || row.codeType === 4) {
  //   row.editCalcQty = proxy.$fn.accAdd(
  //     proxy.$fn.accMul(row.largeUnitQty || 0, row.unitConvertCoefficient || 1),
  //     row.smallUnitQty || 0
  //   )
  //   row.editQty = proxy.$fn.accDiv(
  //     row.editCalcQty || 0,
  //     row.unitConvertCoefficient || 1
  //   )
  //   row.sumAmount = proxy.$fn.accDiv(
  //     proxy.$fn.accMul(row.editCalcQty || 0, parseFloat(row.price || 0)),
  //     row.unitConvertCoefficient || 1
  //   )
  // }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      selectRow.value = data
      dialogInfo.value.btList[1].disabled = !selectRow.value.length
      break
  }
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emits('reset')
}
function getCustomize() {
  let _tableInfo = tableInfo.value
  let _filterInfo = filterInfo.value
  let param = { tableKey: props.tableKey }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      )
      _filterInfo.searchList = searchInfo.searchList
      _filterInfo.searchList.forEach((item) => {
        item.event = search
      })

      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
        ...props.query,
      }
      filterInfo.value.query.queryParams = {
        ...filterInfo.value.query.queryParams,
        ...props.queryParams,
      }
      tableInfo.value.api = props.api
      getList()
    }
  })
}
</script>

<style scoped lang="scss"></style>
